﻿using Core;
using Core.Domain.Customers;
using Net.Web.Models.Resumes;
using Services.Customers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Services.Localization;
using Services.Directory;
using Core.Domain.Common;

namespace Net.Web.Controllers
{
    /// <summary>
    /// 简历控制器
    /// </summary>
    public class ResumesController : BaseController
    {
        
        #region Fields

        private readonly IWorkContext _workContext;
        private readonly IStoreContext _storeContext;
        private readonly IWebHelper _webHelper;
        private readonly ILocalizationService _localizationService;
        private readonly IResumeService _resumeService;
        private readonly ICitysService _cityService;
        private readonly CommonSettings _commonSetting;

        #endregion

        #region Con
        public ResumesController(
            IWorkContext workContext,
            IStoreContext storeContext,
            IWebHelper webHelper,
            ILocalizationService localizationService,
            ICitysService cityService,
            IResumeService resumeService,
            CommonSettings commonSetting)
        {
            this._workContext = workContext;
            this._storeContext = storeContext;
            this._webHelper = webHelper;
            this._resumeService = resumeService;
            this._localizationService = localizationService;
            this._cityService = cityService;
            this._commonSetting = commonSetting;
        }
        #endregion

        public ResumesController()
        { }

        
        /// <summary>
        /// 建立列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult List(ResumeListModel model)
        {
            if (model == null)
                model = new ResumeListModel();

            if (model.Keyword == null)
                model.Keyword = "";

            model.Keyword = model.Keyword.Trim();

            PrepareSortingOptions(model);

            PrepareCity(model);

            PreparePageSizeOptions(model, _commonSetting.AllowCustomersToSelectPageSize, _commonSetting.PageSizeOptions, _commonSetting.PageSize);

            var list = _resumeService.GetResumes(
                        name: model.Keyword,
                        phone: model.Keyword,
                        mail: model.Keyword,
                        cityId: model.City,
                        orderby: (ResumeSortingEnum)model.OrderBy,
                        deleted: false,
                        active: true,
                        pageIndex: model.PageIndex, pageSize: model.PageSize
                );

            model.Resumes = (from p in list
                             select new ResumeOverviewModel
                             {
                                 City = _cityService.GetCityById(p.CityId).Name,
                                 Id = p.Id,
                                 Name = p.Name,
                                 ReadTimes = p.ReadTimes.ToString(),
                                 Sex = p.Sex == Sex.Man ? "男" : "女",
                                 UpdateOn = p.UpdateOn.ToString("MM-dd HH:mm:SS"),
                                 WorkYear = p.WorkYear
                             }).ToList();

            return View(model);
        }


        #region Utilities

        [NonAction]
        protected virtual void PrepareSortingOptions(ResumeListModel pagingFilteringModel)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("pagingFilteringModel");

            foreach (ResumeSortingEnum enumValue in Enum.GetValues(typeof(ResumeSortingEnum)))
            {
                var currentPageUrl = _webHelper.GetThisPageUrl(true);
                var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null);

                pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem()
                {
                    Text = enumValue.GetLocalizedEnum(_localizationService, _workContext),
                    Value = sortUrl,
                    Selected = enumValue == (ResumeSortingEnum)pagingFilteringModel.OrderBy
                });
            }
        }

        [NonAction]
        protected virtual void PrepareCity(ResumeListModel pagingFilteringModel)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("PrepareCity");

            var cities = _cityService.GetCities(hot: true, pageIndex: 0, pageSize: 7);

            var currentPageUrl = _webHelper.GetThisPageUrl(true);
            pagingFilteringModel.AvailableCity = (from p in cities
                                                  select new SelectListItem()
                                                  {
                                                      Text = p.Name,
                                                      Value = _webHelper.ModifyQueryString(currentPageUrl, "city=" + p.Id.ToString(), null),
                                                      Selected = p.Id == pagingFilteringModel.City,
                                                  }).ToList();
        }

        [NonAction]
        protected virtual void PreparePageSizeOptions(ResumeListModel pagingFilteringModel,
            bool allowCustomersToSelectPageSize, string pageSizeOptions, int fixedPageSize)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("pagingFilteringModel");


            if (pagingFilteringModel.PageNumber <= 0)
            {
                pagingFilteringModel.PageNumber = 1;
            }
            if (allowCustomersToSelectPageSize && pageSizeOptions != null)
            {
                var pageSizes = pageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (pageSizes.Any())
                {
                    if (pagingFilteringModel.PageSize <= 0 || !pageSizes.Contains(pagingFilteringModel.PageSize.ToString()))
                    {
                        int temp = 0;

                        if (int.TryParse(pageSizes.FirstOrDefault(), out temp))
                        {
                            if (temp > 0)
                            {
                                pagingFilteringModel.PageSize = temp;
                            }
                        }
                    }

                    var currentPageUrl = _webHelper.GetThisPageUrl(true);
                    var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null);
                    sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber");

                    foreach (var pageSize in pageSizes)
                    {
                        int temp = 0;
                        if (!int.TryParse(pageSize, out temp))
                        {
                            continue;
                        }
                        if (temp <= 0)
                        {
                            continue;
                        }

                        pagingFilteringModel.PageSizeOptions.Add(new SelectListItem()
                        {
                            Text = pageSize,
                            Value = String.Format(sortUrl, pageSize),
                            Selected = pageSize.Equals(pagingFilteringModel.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase)
                        });
                    }

                    if (pagingFilteringModel.PageSizeOptions.Any())
                    {
                        pagingFilteringModel.PageSizeOptions = pagingFilteringModel.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList();

                        if (pagingFilteringModel.PageSize <= 0)
                        {
                            pagingFilteringModel.PageSize = int.Parse(pagingFilteringModel.PageSizeOptions.FirstOrDefault().Text);
                        }
                    }
                }
            }
            else
            {
                pagingFilteringModel.PageSize = fixedPageSize;
            }

            if (pagingFilteringModel.PageSize <= 0)
            {
                pagingFilteringModel.PageSize = fixedPageSize;
            }
        }

        #endregion
    }
}